package com.ac.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ac.aop.Auth;
import com.ac.conf.IndexConfig;
import com.ac.exception.RRException;
import com.ac.model.FileLog;
import com.ac.response.Res;
import com.ac.service.AuthTokenService;
import com.ac.service.FileLogService;
import com.ac.util.FileUtils;

import cn.hutool.core.io.FileUtil;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("file")
@RequiredArgsConstructor
public class FileController {

	private final FileLogService FileLogService;
	private final AuthTokenService ts;

	@Auth
	@PostMapping("/uploadFile")
	public Res uploadFile(@RequestParam("file") MultipartFile file, @RequestHeader("token") String token) {
		try {
			String userId = ts.getUserId(token);
			String filename = file.getOriginalFilename();
			String[] suf = FileUtils.getType(filename);
			if (suf[1] == null)
				throw new RRException("不支持的文件类型");

			FileLog fileLog = new FileLog();
			fileLog.insert();
			fileLog.setSign(FileLog.TempUploadSign);
			String resUrl = "upload/" + userId + "/" + fileLog.getId() + "." + suf[2];
			String url = IndexConfig.staticUrl + resUrl;
			FileUtil.writeFromStream(file.getInputStream(), url);
			fileLog.setUrl(url);
			fileLog.setUserId(userId);
			fileLog.setName("UploadFile");
			fileLog.setType(suf[2]);
			fileLog.setOpen(true);
			FileLogService.insert(fileLog);
			resUrl = "/static_file/" + resUrl;
			Res res = Res.success(null, resUrl);
			return ts.getToken(res, token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RRException("上传失败");
	}

	@GetMapping("/delFile")
	public String delFile(@RequestParam(value = "id") String id) {
//		FilesService.delImage(id);
		return "删除成功";
	}

}
